<template>
  <div>
    <div class="bottom-option-container" :style="'right:' + btm_right">
      <div class="btm-hide" @click="hideBottomOptions">
        <svg class="icon" aria-hidden="true"><use :xlink:href="btm_icon"></use></svg>
      </div>
      <div
        class="btm-opt"
        @click="router.push('/p/income')"
        style="background-color: #88d6b0;"
      >记收入</div>
      <div
        class="btm-opt"
        @click="router.push('/p/expense')"
        style="background-color: #5aa9d7;"
      >记支出</div>
    </div>
    <div class="bill-container">
      <div class="filter-area">
        <div class="type">
          <el-select v-model="filterForm.type" style="width: 120px;">
            <el-option
              v-for="item in billListType"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="refresh">
          <div class="refresh-txt" @click="doRefresh">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-gongnengkaiguan"></use>
            </svg>
            刷新
          </div>
        </div>
      </div>
      <div class="info-area">
        <div class="date-picker">
          <el-date-picker
            type="month"
            v-model="filterForm.date"
            style="width: 120px;"
            :clearable="false"
            value-format="x"
          />
        </div>
        <div class="info-cal" @click="openDetailTotal">
          总收入￥{{ total.income }}&emsp;总支出￥{{ total.expense }}
        </div>
      </div>
      <div class="detail-area" v-loading="loadingList">
        <div class="bill-item" v-for="bl in itemList" @click="openDetailDialog(bl.note, bl.accountId)">
          <div class="item">
            <div class="bl-detail">
              <div class="bl-title">
                {{ classTrans(bl.income, bl.categoryId) }}
              </div>
              <div class="bl-date">
                {{ timeTrans(bl.transactionDate) }}
              </div>
            </div>
            <div
              class="bl-amount"
              :style="{ color: bl.income ? '#870101' : '#1D8704' }"
            >￥{{ bl.amount }}</div>
          </div>
        </div>
      </div>
      <div class="end-area">已经到底了 :)</div>
    </div>
    <Dialog
      title="账目详情"
      @close-dialog="detailDialog = false;" 
      :visible="detailDialog"
      :maskBtn="true"
      :width="250"
      :button-list="btnList"
    >
      备注: {{ curDesc }}
    </Dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, computed, onMounted, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { throttle } from '@/utils/tools';
  import message from '@/utils/message';
  import Dialog from '@/components/Dialog.vue';
  import { useUserStore } from '@/stores/user';
  import { getMonthBillList, deleteBillItem } from '@/utils/api';
  import { hashMapConstant, billClassList, incomeClassList } from '@/utils/constant';

  const router = useRouter();
  const useUser = useUserStore();
  let itemList = ref([]);
  let loadingList = ref(true);

  let btm_right = ref('0px');
  let btm_icon = ref('#icon-you1');
  function hideBottomOptions() {
    if(btm_right.value === '0px') {
      btm_right.value = '-185px';
      btm_icon.value = '#icon-zuo';
    } else {
      btm_right.value = '0px';
      btm_icon.value = '#icon-you1';
    }
  }

  const billListType = [
    { label: '全部账单', value: 'all' },
    { label: '收入', value: 'income' },
    { label: '支出', value: 'expense' }
  ];
  let filterForm = reactive({
    type: 'all',
    date: (new Date()).getTime(),
  });
  let total = computed(() => {
    // 根据当月账单计算总支出和收入
    let income = 0;
    let expense = 0;
    itemList.value.forEach((itm) => {
      if(itm.income) expense += itm.amount;
      else income += itm.amount;
    });
    return { income, expense };
  });

  watch(filterForm, () => {
    getBillInfo();
  });
  const doRefresh = async () => {
    const ans = await getBillInfo();
    if(ans) message.success('刷新成功！');
    else message.warning('刷新失败，请重试！');
  };
  const openDetailTotal = () => {
    message.confirm(
      `总收入￥${total.value.income} 总支出￥${total.value.expense}`, 
      '月度统计'
    );
  };

  let curDesc = ref('无');
  let curBid = ref(-1);
  let detailDialog = ref(false);
  const btnList = [{
    type: 'danger',
    name: '删除该记录',
    btnEvent: () => {
      message.confirm(
        '确认删除该账目？', 
        '操作',
        'warning',
        () => { // success
          deleteBillItem(curBid.value)
            .then(res => {
              if(res.data) {
                message.success('删除成功');
                detailDialog.value = false;
                getBillInfo();
              } else {
                message.warning('删除失败，请重试');
              }
            })
            .catch(err => {
              message.warning('系统错误，请重试');
              console.warn(err);
            });
        }
      );
    },
    dis: false
  }];
  const openDetailDialog = (desc, bid) => {
    console.log("del: ", bid);
    curDesc.value = desc ? desc : '无';
    curBid.value = bid ? bid : -1;
    detailDialog.value = true;
  };

  function timeTrans(t) {
    const timeObj = new Date(t);
    const month = (timeObj.getMonth() + 1).toString();
    const day = (timeObj.getDate()).toString();
    const hour = (timeObj.getHours()).toString();
    const min = (timeObj.getMinutes()).toString();
    return `${month.padStart(2, '0')}-${day.padStart(2, '0')} ${hour.padStart(2, '0')}:${min.padStart(2, '0')}`;
  }

  function classTrans(income, id) {
    if(income)
      return hashMapConstant(billClassList, id, 'id', 'value', '其它');
    else
      return hashMapConstant(incomeClassList, id, 'id', 'value', '其它');
  }

  const getBillInfo = async () => {
    let flag = false;
    loadingList.value = true;
    await getMonthBillList(filterForm.type, filterForm.date, useUser.userID)
      .then((res) => {
        if(res.data.msg === "成功") {
          itemList.value = res.data.data;
          flag = true;
        } else {
          message.error(res.data.msg || '获取账单失败！', 1200);
          itemList.value = [];
          flag = false;
        }
        loadingList.value = false;
      })
      .catch(err => {
        message.warning("系统错误，请重试！");
        console.warn(err);
        itemList.value = [];
        flag = false;
        loadingList.value = false;
      });
    return flag;
  };

  onMounted(() => {
    getBillInfo(); // 获取账单信息
  });

  window.addEventListener('scroll', throttle(() => {
    btm_right.value = '-185px';
    btm_icon.value = '#icon-zuo';
  }, 500));
</script>

<style lang="scss" scoped>
  .bottom-option-container{
    width: fit-content;
    height: 45px;
    position: fixed;
    bottom: 70px;
    display: flex;
    justify-content: center;
    align-items: center;
    transition: right 1s ease;
    .btm-opt{
      width: 75px;
      line-height: 35px;
      text-align: center;
      margin-right: 15px;
      border-radius: 12px;
      color: white;
      box-shadow: 0 0 3px $theme-shadow0;
      cursor: pointer;
    }
    .btm-hide{
      width: 35px;
      line-height: 35px;
      margin-right: 10px;
      border-radius: 50%;
      text-align: center;
      font-size: 15px;
      background-color: white;
      box-shadow: 0 0 3px $theme-shadow0;
      cursor: pointer;
    }
  }
  .bill-container{
    width: 100%;
    .filter-area{
      position: fixed;
      top: 50px;
      left: 0;
      width: 100%;
      height: 45px;
      background-color: $theme-shadow00;
      .type{
        float: left;
        height: 45px;
        display: flex;
        align-items: center;
        margin-left: 10px;
      }
      .refresh{
        display: flex;
        align-items: center;
        float: right;
        height: 45px;
        width: fit-content;
        font-size: 14px;
        color: grey;
        margin-right: 10px;
        cursor: pointer;
        .refresh-txt{
          line-height: 32px;
          padding: 0 7px 0 7px;
          background-color: white;
          border-radius: 8px;
          border: 1.5px solid #e4e7ed;
        }
      }
      .refresh:hover .refresh-txt{
        box-shadow: inset 0 0 5px $theme-shadow;
      }
    }
    .info-area{
      position: fixed;
      top: 95px;
      left: 0;
      width: 100%;
      height: 45px;
      background-color: white;
      box-shadow: 0 2px 5px $theme-shadow00;
      .date-picker{
        float: left;
        height: 45px;
        display: flex;
        align-items: center;
        margin-left: 10px;
      }
      .info-cal{
        width: 200px;
        float: right;
        text-align: right;
        line-height: 45px;
        font-size: 15px;
        color: $theme-shadow;
        margin-right: 10px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        cursor: pointer;
      }
      .info-cal:hover{
        color: $theme-main-dark;
      }
    }
    .detail-area{
      margin-top: 140px;
      .bill-item{
        width: 100%;
        height: 70px;
        cursor: pointer;
      }
      .bill-item:hover{
        background-color: $theme-shadow00;
      }
    }
    .item{
      width: 93%;
      height: 70px;
      margin: auto;
      border-top: 1px solid $theme-shadow00;
      .bl-detail{
        float: left;
        height: 70px;
        margin-left: 10px;
        .bl-title{
          line-height: 40px;
          font-size: 16px;
          color: $theme-main-dark;
        }
        .bl-date{
          line-height: 30px;
          font-size: 14px;
          color: $theme-shadow;
        }
      }
      .bl-amount{
        float: right;
        line-height: 70px;
        font-size: 19px;
        margin-right: 10px;
        color: $theme-main-dark;
      }
    }
    .end-area{
      width: 100%;
      line-height: 45px;
      text-align: center;
      font-size: 13px;
      margin-top: 10px;
      color: $theme-shadow;
      background-color: white;
      user-select: none;
    }
  }
</style>